﻿#-*- coding:utf-8 -*-
from django.shortcuts import render_to_response
from django.http import HttpResponse,HttpResponseRedirect
import MySQLdb,simplejson,sys,os,urllib,re,datetime,time,md5,hashlib,random,calendar,json,xlwt
import StringIO,qrcode

from zweixin.client import WeixinAPI,WeixinMpAPI
from zweixin.oauth2 import OAuth2AuthExchangeError

from zzwx.client import Client
from zz91settings import weixinconfig
from zz91db_dibang import dibangdb
from zz91tools import formattime,int_to_strall

APP_ID = weixinconfig['erm']['appid']
APP_SECRET = weixinconfig['erm']['secret']

wxc = Client(APP_ID, APP_SECRET)

REDIRECT_URI = 'http://erm.zz91.com/wechat/redirect_uri.html'
api = WeixinMpAPI(appid=APP_ID,
                app_secret=APP_SECRET,
                redirect_uri=REDIRECT_URI)
dbd=dibangdb(1)
reload(sys)
sys.setdefaultencoding('UTF-8')
nowpath=os.path.dirname(__file__)
execfile(nowpath+"/func/erm_function.py")
execfile(nowpath+"/func/ermtools.py")
zzdibang=zzdibang()

#微信授权登陆
def auth_login(request):
    scope = ("snsapi_base", )
    authorize_url = api.get_authorize_url(scope=scope)
    tourl=request.GET.get("tourl")
    if tourl:
        request.session['tourl']=tourl
    return HttpResponseRedirect(authorize_url)
def redirect_uri(request):
    code=request.GET.get("code")
    gmt_created=gmt_modified=datetime.datetime.now()
    access_token = api.exchange_code_for_access_token(code=code)
    openid_fw=access_token['openid']
    request.session['openid_fw']=openid_fw
    tourl=request.session.get("tourl")
    #return HttpResponse(openid_fw)
    sql='select id,group_id,selfid,company_id,utype,username from users where weixinid=%s and isdel=0'
    result=dbd.fetchonedb(sql,[openid_fw])
    if result:
        user_id=result['id']
        group_id=result['group_id']
        user_selfid=result['selfid']
        company_id=result['company_id']
        username=result['username']
        utype=result['utype']
        request.session.set_expiry(6000*60000)
        request.session['user_id']=user_id
        request.session['username']=username
        request.session['group_id']=group_id
        request.session['user_selfid']=user_selfid
        request.session['company_id']=company_id
        request.session['utype']=utype
    if not tourl:
        tourl="http://erm.zz91.com/mobile/index.html"
    return HttpResponseRedirect(tourl)

def weixinautologin(request):
    weixinid=request.GET.get("weixinid")
    sql='select id,group_id,selfid,company_id,utype,username from users where weixinid=%s and isdel=0'
    result=dbd.fetchonedb(sql,[weixinid])
    if result:
        user_id=result['id']
        group_id=result['group_id']
        user_selfid=result['selfid']
        company_id=result['company_id']
        username=result['username']
        utype=result['utype']
        request.session.set_expiry(6000*60000)
        request.session['user_id']=user_id
        request.session['username']=username
        request.session['group_id']=group_id
        request.session['user_selfid']=user_selfid
        request.session['company_id']=company_id
        request.session['utype']=utype
    return ''
#----订单消息提醒
def weixintixin(storage_selfid=""):
    if storage_selfid:
        weixinid=''
        sql="select company_id from storage where selfid=%s"
        result=dbd.fetchonedb(sql,[storage_selfid])
        if result:
            company_id=result["company_id"]
            sql="select weixinid from users where company_id=%s and wxtixin=1"
            result=dbd.fetchalldb(sql,[company_id])
            if result:
                for list in result:
                    weixinid=list['weixinid']
                    sendwxxiaoxi(weixinid,storage_selfid)
                    
#----发送微信消息提醒
def sendwxxiaoxi(weixinid,storage_selfid):
    if weixinid:
        sql="select code,gmt_created,suppliers_selfid,company_id from storage where selfid=%s"
        result=dbd.fetchonedb(sql,[storage_selfid])
        if result:
            code=result['code']
            gmt_created=formattime(result['gmt_created'],2)
            suppliersname=zzdibang.getsuppliername(result['suppliers_selfid'])
            companyname=zzdibang.getcompanyname(result['company_id'])
            datava={
                "touser":weixinid,
                "template_id":"vRDToeNPti8TbiQrouc-A1QSk8ehWvZu4UrKEmEiCw4",
                "url":"http://erm.zz91.com/mobile/pricing_show.html?storage_selfid="+str(storage_selfid)+"&weixinid="+str(weixinid),
                "topcolor":"#FF0000",
                "data":{
                    "first": {
                    "value":"有新的待定价订单，请尽快定价！",
                    "color":"#173177"
                    },
                    "keyword1":{
                    "value":str(code),
                    "color":"#173177"
                    },
                    "keyword2":{
                    "value":gmt_created,
                    "color":"#173177"
                    },
                    "keyword3":{
                    "value":suppliersname,
                    "color":"#173177"
                    },
                    "keyword4":{
                    "value":companyname,
                    "color":"#173177"
                    },
                    "remark":{
                    "value":"点击查看入库单，并定价",
                    "color":"#173177"
                    },
                }
            }
            datava=json.dumps(datava,ensure_ascii=False,indent=2)
            token=wxc.send_template_message(datava)
            
#群发报价提醒
def qunfa_price(weixinid,company_id,todayprice,cdate,price_sub_id):
    if weixinid:
        gmt_created=datetime.datetime.now()
        sql="select id from price_qunfa_log where weixinid=%s and price_sub_id=%s"
        result=dbd.fetchonedb(sql,[weixinid,price_sub_id])
        if not result:
            companyname=zzdibang.getcompanyname(company_id)
            datava={
                "touser":weixinid,
                "template_id":"n5T7skCURHSNRRWGLRzyIaAqKaL7sMVsEFrH4EQG5ck",
                "url":"http://erm.zz91.com/wechat/auth_login.html?tourl=/mobile/priceview.html",
                "topcolor":"#FF0000",
                "data":{
                    "first": {
                    "value":str(cdate)+"最新报价！",
                    "color":"#173177"
                    },
                    "keyword1":{
                    "value":str(cdate),
                    "color":"#173177"
                    },
                    "keyword2":{
                    "value":companyname,
                    "color":"#173177"
                    },
                    "keyword3":{
                    "value":'',
                    "color":"#173177"
                    },
                    "keyword4":{
                    "value":todayprice,
                    "color":"#173177"
                    },
                    "remark":{
                    "value":"点击查看",
                    "color":"#173177"
                    },
                }
            }
            datava=json.dumps(datava,ensure_ascii=False,indent=2)
            token=wxc.send_template_message(datava)
            sql="insert into price_qunfa_log(weixinid,company_id,qdate,price_sub_id,gmt_created) values(%s,%s,%s,%s,%s)"
            dbd.updatetodb(sql,[weixinid,company_id,cdate,price_sub_id,gmt_created])
            

#创建二维码ticket
def getqrcode(request):
    company_id=request.GET.get("company_id")
    #{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": 123}}}
    data={"action_name": "QR_LIMIT_SCENE", "action_info":  {"scene": {"scene_id": int(company_id)}}}
    token=wxc.create_qrcode(data)
    #return HttpResponse(str(token))
    img=wxc.show_qrcode(token['ticket'])
    return HttpResponseRedirect(img)
    return HttpResponse("<img src='"+img+"' />")